import axios from "axios";
import {ElMessage}  from "element-plus";
import {useTokenStore} from "../stores/token.js"

const request = axios.create({
    baseURL: 'http://localhost:9090',
    timeout: 30000,//后台接口超时时间
})

//request拦截器
//可以自请求发送前对请求做一些处理
request.interceptors.request.use(
    config=>{
        config.headers['Content-Type']='application/json;charset=utf-8';
        //添加token
        const tokenStore = useTokenStore();

        if (tokenStore.token){
            config.headers.Authorization = tokenStore.token
        }

    return config
},error=>{
    return Promise.reject(error)
});

import router from "../router";
//request拦截器
//可以在接口响应后统一处理结果
request.interceptors.response.use(

    response => {
        let res = response.data;
        //兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res;
        }

        const tokenStore = useTokenStore();



        return res;
    },
    error=>{
        if (error.response.status === 404){
            ElMessage.error("未找到接口")
        }else if (error.response.status === 500){
            ElMessage.error("系统异常，查看后端控制台报错")
        }else if (error.response.status === 401){
            ElMessage.error("请先登录")
            router.push("/login")
        }
        else {
            console.error(error.message)
        }
        return Promise.reject(error)
    }
)

export default request